package com.itheima.practice.config;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.document.Document;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Configuration
public class VectorStoreConfig {

    @Bean
    public VectorStore ruleVectorStore(OpenAiEmbeddingModel embeddingModel) {
        // 总是返回一个VectorStore实现
        // 先尝试创建基于OpenAI的VectorStore
        try {
            SimpleVectorStore vectorStore = SimpleVectorStore.builder(embeddingModel)
                    .build();

            // 加载 rules.json
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream("rules.json");
            if (inputStream != null) {
                String jsonStr = IoUtil.readUtf8(inputStream);
                List<Map> rules = JSONUtil.toList(JSONUtil.parseArray(jsonStr), Map.class);

                List<Document> documents = rules.stream()
                    .map(rule -> new Document(
                        (String) rule.get("description"),
                        Map.of("id", rule.get("id"), "type", rule.get("type"))
                    ))
                    .toList();

                vectorStore.add(documents);
            }
            System.out.println("Successfully initialized vector store with OpenAI embeddings");
            return vectorStore;
        } catch (Exception e) {
            // 如果无法连接到OpenAI或其他问题，则返回一个空的向量存储
            System.err.println("Warning: Unable to initialize vector store with OpenAI embeddings: " + e.getMessage());
            System.err.println("Using empty vector store instead.");
            
            // 返回一个简单的VectorStore实现，所有操作都是空实现
            return new VectorStore() {
                @Override
                public void add(List<Document> documents) {
                    // 空实现
                    System.out.println("Warning: Using fallback VectorStore, add operation ignored");
                }

                @Override
                public List<Document> similaritySearch(SearchRequest searchRequest) {
                    System.out.println("Warning: Using fallback VectorStore, similarity search returns empty result");
                    return List.of(); // 返回空列表
                }
                
                @Override
                public void delete(List<String> idList) {
                    // 空实现
                }
                
                @Override
                public void delete(org.springframework.ai.vectorstore.filter.Filter.Expression filter) {
                    // 空实现
                }
              
            };
        }
    }
}